package com.example.demo.web.util;

import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class MQTTUtil implements ApplicationRunner {

    /**MQTT服务端ip及端口*/
    private static String host = "ws://127.0.0.1:8083";

    /**账号*/
    private static String username = "admin";

    /**密码*/
    private static String password = "public";

    /**订阅的主题*/
    private static String subTopic = "tlock";

    /**MQTT-Client*/
    private static MqttClient client;
    private Logger logger = LogManager.getLogger(MQTTUtil.class);
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
    	 this.connect();
    }

    private void connect() throws Exception{ 
    	String clientid = UUID.randomUUID().toString();
    	client = new MqttClient(host,clientid, new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();                                      
        options.setCleanSession(false);  
        options.setUserName(username);  
        options.setPassword(password.toCharArray());  
        options.setCleanSession(false);   //是否清除session
        // 设置超时时间  
        options.setConnectionTimeout(30);  
        // 设置会话心跳时间  
        options.setKeepAliveInterval(20);  
        try {  
            client.setCallback(new PushCallback(client,options,subTopic,0));  
            client.connect(options);
            client.subscribe(subTopic,0); 
            logger.info("MQTT连接成功:"+clientid+":"+client);
        } catch (Exception e) {  
            logger.error("MQTT连接异常："+e);
        }  
    }  
    
    
    /**
     * 重连
     * @throws Exception
     */
    public void reConnect() throws Exception {
    	        if(null != client) {
    	        	this.connect();
             }
       }
    
    /**
     * 订阅某个主题
     * @param topic
     * @param qos
     */
    public void subscribe(String topic,int qos){
        try {
        	logger.info("topic:"+topic);
        	client.subscribe(topic, qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
    
    public static void publish(String pubTopic, String content) {
        
        try {
            MqttTopic topic = MQTTUtil.getClient().getTopic(pubTopic);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(0);
            topic.publish(message);
            System.out.println("MQTT Send:" + content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	public static MqttClient getClient() {
		return client;
	}

	public static void setClient(MqttClient client) {
		MQTTUtil.client = client;
	}
}
